<template>
  <slide-view
    v-empty="!canShowDetail"
    :listener-ids="listenerIDs"
    :no-listener-ids="noListenerIDs"
    :no-listener-class="noListenerClass"
    :body-style="{padding: 0, height: '100%'}"
    xs-empty-icon="nopermission"
    :xs-empty-text="$t('crm.product.40ab91a8395b85c5cdbf2a6b54d90374')"
    @afterEnter="viewAfterEnter"
    @close="hideView">
    <div ref="crmDetailMain" v-loading="loading" class="detail-main no-padding">
      <flexbox
        v-if="canShowDetail && detailData"
        direction="column"
        align="stretch"
        class="d-container">
        <wk-detail-header
          :subtitle="$t('crm.product.0a0faa5800b4335b5d413d34c1b753f0')"
          :class="{'is-shadow': bodyIsScroll}"
          :title="detailData.name"
          :page-list="pageList"
          :dropdowns="handleOperations"
          @command="headerRightClick"
          @pageChange="pageChange"
        >
          <template slot="left">
            <el-tooltip :content="detailData.star == 0 ? '添加关注' : '取消关注'" effect="dark" placement="top">
              <i
                v-if="detailData.star == 0"
                class="el-icon-star-off focus-icon"
                @click="toggleStar()" />
              <i
                v-else
                class="wk wk-focus-on focus-icon active"
                @click="toggleStar()" />
            </el-tooltip>
          </template>

          <template slot="right">
            <time-piece v-if="showTimer && isCall" />
            <el-button
              v-if="showTransfer"
              class="head-handle-button"
              @click="headerRightClick('transfer')">
              {{ $t('crm.product.578d2590714fd2d4ed0c39e02955a747') }}
            </el-button>
            <el-button
              v-if="showEdit"
              class="head-handle-button"
              type="primary"
              @click="headerRightClick('edit')">
              {{ $t('crm.product.b6b2b8656427328c1a2da5432df76477') }}
            </el-button>
          </template>
        </wk-detail-header>

        <!-- 标签 -->
        <flexbox v-if="tagInfo" wrap="wrap" class="wk-tags-content">
          <tag-view :value="tagInfo.value" :max-length="Infinity" wrap="wrap">
            <wk-tag
              v-model="tagInfo.value"
              :disabled="tagInfo.disabled"
              :placeholder="tagInfo.placeholder"
              :data="tagInfo"
              :options="tagInfo.setting"
              @change="tagChange($event)">
              <el-tooltip
                slot="reference"
                :content="$t('crm.product.9e9d9206ec13a003df269d676de1a455')"
                effect="dark"
                placement="top">
                <el-button
                  type="icon"
                  size="small"
                  icon="wk wk-icon-label-solid" />
              </el-tooltip>
            </wk-tag>
          </tag-view>
        </flexbox>

        <div class="d-container-body" @scroll="bodyScroll">
          <detail-head-base :list="headDetails" />
          <relative-stage-records
            :id="id"
            :crm-type="crmType"
            :is-stage-flow="true"
            :detail="detailData"
            @handle="detailHeadHandle" />
          <el-tabs v-model="tabCurrentName" nav-mode="more" class="top-padding">
            <el-tab-pane
              v-for="(item, index) in tabNames"
              :key="index"
              :label="item.label"
              :name="item.name"
              lazy>
              <template slot="label">
                <el-badge
                  :value="item.num"
                  :hidden="item.num <= 0"
                  type="primary">
                  {{ item.label }}
                </el-badge>
              </template>
              <c-r-m-edit-base-info
                :is="item.name"
                v-if="item.name === 'CRMEditBaseInfo'"
                :id="id"
                :ref="item.name"
                :detail="detailData"
                :crm-type="crmType"
                :ignore-fields="['status']"
                @handle="detailHeadHandle">
                <sections
                  class="b-cells"
                  :title="$t('crm.product.e86f0c9c0d7869e8aafea9b50f4db89e')"
                  content-height="auto">
                  <div class="image">
                    <div v-if="mainFileList.length > 0" class="image-info">
                      <div class="image-info__label">
                        {{ $t('crm.product.79a9b0de112b5fe3cdad49294de2d4ef') }}
                      </div>
                      <div class="image-info__list">
                        <img
                          v-for="(mItem, mIndex) in mainFileList"
                          :key="mIndex"
                          v-src="mItem.url"
                          class="main-img"
                          @click="previewImage(mainFileList, index)">
                      </div>
                    </div>
                    <div v-if="detailFileList.length > 0" class="image-info">
                      <div class="image-info__label">
                        {{ $t('crm.product.7f03386695afa231ea3bcdb0e08b025b') }}
                      </div>
                      <div class="image-info__list">
                        <img
                          v-for="(dItem, dIndex) in detailFileList"
                          :key="dIndex"
                          v-src="dItem.url"
                          class="detial-img"
                          @click="previewImage(detailFileList, dIndex)">
                      </div>
                    </div>
                    <div
                      v-if="detailFileList.length == 0 && mainFileList.length == 0"
                      class="no-img">
                      {{ $t('crm.product.42a9518047ed1ee9e2bbb40f46c798ec') }}
                    </div>
                  </div>
                </sections>
              </c-r-m-edit-base-info>
              <component
                :is="item.name"
                v-else
                :id="id"
                :detail="detailData"
                :crm-type="crmType"
                @handle="detailHeadHandle" />
            </el-tab-pane>
          </el-tabs>
        </div>
      </flexbox>
    </div>

    <!-- 新建编辑 -->
    <c-r-m-all-create
      v-if="crmCreateShow"
      :action="createActionInfo"
      :crm-type="crmType"
      @save-success="editSaveSuccess"
      @close="crmCreateShow=false" />

    <!-- 转移 -->
    <transfer-handle
      v-if="transferDialogShow"
      :props="transferHandleProps"
      :dialog-visible.sync="transferDialogShow"
      @handle="detailHeadHandle({type: 'transfer'})" />
  </slide-view>
</template>

<script>
import {
  crmProductReadAPI,
  crmProductDeleteAPI,
  crmProductStatusAPI
} from '@/api/crm/product'

import SlideView from '@/components/SlideView'
import TransferHandle from '@/components/Page/SelectionHandle/TransferHandle' // 转移
import RelativeStageRecords from '../components/RelativeStageRecords' // 阶段记录
import CRMEditBaseInfo from '../components/CRMEditBaseInfo' // 产品基本信息
import RelativeFiles from '../components/RelativeFiles' // 相关附件
import RelativeHandle from '../components/RelativeHandle' // 相关操作

import CRMAllCreate from '../components/CRMAllCreate' // 新建页面
import DetailImg from './components/DetailImg'
import Sections from '../components/Sections'

import DetailMixin from '../mixins/Detail'
import { separator } from '@/filters/vueNumeralFilter/filters'

export default {
  // 客户管理 的 产品详情
  name: 'ProductDetail',
  components: {
    SlideView,
    TransferHandle,
    RelativeStageRecords,
    DetailImg,
    CRMEditBaseInfo,
    RelativeFiles,
    RelativeHandle,
    CRMAllCreate,
    Sections
  },
  mixins: [DetailMixin],
  props: {
    // 详情信息id
    id: [String, Number],
    // 监听的dom 进行隐藏详情
    listenerIDs: {
      type: Array,
      default: () => {
        return ['crm-main-container']
      }
    },
    // 不监听
    noListenerIDs: {
      type: Array,
      default: () => {
        return []
      }
    },
    noListenerClass: {
      type: Array,
      default: () => {
        return ['el-table__body']
      }
    }
  },
  data() {
    return {
      // 展示加载loading
      loading: false,
      crmType: 'product',
      headDetails: [],
      tabCurrentName: 'CRMEditBaseInfo'
    }
  },
  computed: {
    // 可操作选项
    handleOperations() {
      return this.getOperations(['delete', 'start', 'disable'])
    },

    // tabs
    tabNames() {
      const tempsTabs = [
        { label: this.$t('crm.product.b70222d9ef5dd8a90de6b40cced4e284'), name: 'CRMEditBaseInfo' },
        { label: this.$t('crm.product.3b1337dc9cd766e2c3d66945e6f8a2f3'), num: this.tabsNumber.fileCount, name: 'RelativeFiles' }
      ]
      if (!this.isWxUser) {
        tempsTabs.push({ label: this.$t('crm.product.cae470d3bc72776ea13eca4b7e745f63'), name: 'RelativeHandle' })
      }
      return tempsTabs
    },
    mainFileList() {
      if (this.detailData && this.detailData.mainFileList) {
        return this.detailData.mainFileList
      }

      return []
    },

    detailFileList() {
      if (this.detailData && this.detailData.detailFileList) {
        return this.detailData.detailFileList
      }

      return []
    }
  },
  mounted() {},
  methods: {
    /**
     * 详情
     */
    getDetial() {
      this.loading = true
      crmProductReadAPI({
        productId: this.id
      })
        .then(res => {
          this.loading = false
          const resData = res.data || {}
          this.detailData = resData

          this.headDetails = [
            { title: this.$t('crm.product.55ba766da46343ef9adfbabfa9bc745f'), value: resData.categoryName },
            { title: this.$t('crm.product.83f781070ea2fc8382d36c9e031c4c61'), value: resData.unit },
            { title: `产品价格（${this.crmMoneyUnit}）`, value: separator(this.crmMoney(resData.price || 0)) },
            { title: this.$t('crm.product.903eab2c1ebcdde212b931d39575857b'), value: resData.num }
          ]
        })
        .catch(() => {
          this.loading = false
          this.hideView()
        })
    },

    /**
     * 关闭
     */
    hideView() {
      this.$emit('hide-view')
    },

    /**
     * 预览图片
     */
    previewImage(list, index) {
      this.$wkPreviewFile.preview({
        index: index,
        data: list
      })
    },

    /* ------------------------ 头部事件 ------------------------ */
    /**
     * @description: 头部右侧点击事件
     * @param {*}
     * @return {*}
     */
    headerRightClick(type) {
      if (type === 'transfer') {
        this.transferDialogShow = true
      } else if (type === 'edit') {
        this.createCRMType = this.crmType
        this.createActionInfo = {
          type: 'update',
          id: this.id,
          batchId: this.detailData.batchId,
          editDetail: this.detailData
        }
        this.crmCreateShow = true
      } else if (type == 'delete') {
        this.$confirm(
          this.$t('crm.product.2d2336be09dfcc5a72c52bc761ca7ec6'),
          this.$t('crm.product.cb6584b6362873947a3b693d6a03d6d8'),
          {
            confirmButtonText: this.$t('crm.product.2d04d9d7e902e1d0fc5fe2ca03801c57'),
            cancelButtonText: this.$t('crm.product.1a9bb657bcaa97d8b16889432d2701e7'),
            type: 'warning'
          }
        )
          .then(() => {
            crmProductDeleteAPI([this.id])
              .then(res => {
                this.$message({
                  type: 'success',
                  message: this.$t('crm.product.acd595618ca5f09c555ce40747fc59c3')
                })
                this.detailHeadHandle({ type })
              })
              .catch(() => {})
          })
          .catch(() => {})
      } else if (type === 'start' || type === 'disable') {
        this.$confirm({
          start: this.$t('crm.product.e3f8ce0e0f01e17c613c10677f2e4465'),
          disable: this.$t('crm.product.07ea0c3db40aa823f5527b8016f05f60')
        }[type], this.$t('crm.product.3ff9950ccd4d109532bdd888f988a221'), {
          confirmButtonText: this.$t('crm.product.301e003f2612b91876709b49cc4faa50'),
          cancelButtonText: this.$t('crm.product.d183b56c145f819dcc0ce8eefd6dfd26'),
          type: 'warning'
        })
          .then(() => {
            crmProductStatusAPI({
              ids: [this.id],
              status: type === 'start' ? '1' : '0'
            })
              .then(res => {
                this.$message({
                  type: 'success',
                  message: this.$t('crm.product.ae25cf17098a3d4834409d472b30cf9a')
                })
                this.detailHeadHandle({ type })
              })
              .catch(() => {})
          })
          .catch(() => {})
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../styles/crmdetail.scss";

.d-container-body {
  margin-top: 8px;
}

.image {
  color: $--color-text-primary;

  &-info {
    margin: 10px 25px 0;

    &__label {
      font-size: 13px;
    }

    &__list {
      overflow-x: auto;
      white-space: nowrap;

      img {
        margin-top: 15px;
        cursor: pointer;
        border-radius: $--border-radius-base;
      }

      img + img {
        margin-left: 20px;
      }

      .main-img {
        width: 100px;
        height: 76px;
        object-fit: contain;
        vertical-align: top;
      }

      .detial-img {
        width: 100px;
        height: 80px;
        object-fit: contain;
        vertical-align: top;
      }
    }
  }

  .no-img {
    margin: 50px 0;
    color: $--color-text-regular;
    text-align: center;
  }
}
</style>
